//
//网络辅助类
//


import 'dart:io';

import 'package:dio/io.dart';
import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http_proxy/http_proxy.dart';
import 'package:wch/helper/proxy_helper.dart';
import 'package:wch/main.dart';
import 'package:wch/model/device_list_entity.dart';
import 'package:wch/model/device_version_entity.dart';
import 'package:wch/model/hospital.dart';
import 'package:wch/model/hospital_congig_entity.dart';
import 'package:wch/model/login_model.dart';
import 'package:wch/model/patient_device_list_entity.dart';
import 'package:wch/model/patient_template.dart';
import 'package:wch/model/report_detail_entity.dart';
import 'package:wch/model/report_list_entity.dart';
import 'package:wch/utils/encryption_utils.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wch/utils/loading_utils.dart';

import '../constant/config_constant.dart';
import '../constant/text_constant.dart';
import '../helper/preferences_helper.dart';
import '../model/dcotor.dart';
import '../model/patient_detail.dart';
import '../model/patient_edit.dart';
import '../model/patient_label.dart';
import '../model/patient_list.dart';
import '../networking/api.dart';
import '../utils/log_utils.dart';
import '../utils/toast_utils.dart';
import 'package:dio/dio.dart';

const connectTimeout = 10000;
const receiveTimeout = 10000;
const contentType = 'application/json';
const okCode = 200;
const okCodeStr = '200';

class NetBusiness {
  final Dio _downloadDio = Dio(
      BaseOptions(
          baseUrl: baseUrl,
          connectTimeout: const Duration(milliseconds: 30000),
          receiveTimeout: const Duration(milliseconds: 30000),
          contentType: contentType,
          headers: {
            'token': PreferencesHelper.getUserToken(),
            'channel': 'HOSPITAL_SAAS',
            'language': 'zh-cn',
            'versionNum': appVersion,
          })
  );
  final Dio _dio = Dio(
    BaseOptions(
        baseUrl: baseUrl,
        connectTimeout: const Duration(milliseconds: connectTimeout),
        receiveTimeout: const Duration(milliseconds: receiveTimeout),
        contentType: contentType,
        headers: {
          'token': PreferencesHelper.getUserToken(),
          // 'appType': Platform.isAndroid ? 'XR_DREAM_ANDROID' : 'XR_DREAM_IOS',
          // 'aliyunMobileDeviceToken': PreferencesHelper.getAppId(),
          'channel': 'HOSPITAL_SAAS',
          'language': 'zh-cn',
          'versionNum': appVersion,
        }),
  )
    ..interceptors.add(InterceptorsWrapper(
      onError: (DioException e, ErrorInterceptorHandler handler) {
        LogUtils.log('============onError 拦截器=============');
        LogUtils.log("发生错误：${e.message}");
        // Loading.getIns().hide();
        // Loading.getIns().info(msg: '请求失败，请稍后再试');
        return handler.next(e);
      },
      onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
        // LogUtils.log('============onRequest 拦截器=============');
        if (!isNetworking) {
          ToastUtils.showToast(msg: '当前网络不可用');
          return;
        }
        return handler.next(options);
      },
      onResponse:
          (Response response, ResponseInterceptorHandler handler) async {
        // LogUtils.log('============onResponse 拦截器=============');
        int errorCode = response.statusCode!;
        // LogUtils.log('状态码：$errorCode');
        if (errorCode == okCode) {
          dynamic code = response.data['code'];
          // LogUtils.log('code=$code');
          if (code == '1000' || code == 1000 || code == '1001' ||
              code == 1001) {
            ///登录失效
            // NavigatorUtil.replace(context, page)
            ToastUtils.showToast(msg: '登录失效，请重新登陆');
            WCHApp.navigatorKey.currentState!
                .pushNamedAndRemoveUntil('/login', (route) => route == null);
            // return await handler.reject(DioError(error: DioErrorType.cancel));
            return;
          }
        } else {}
        return handler.next(response);
      },
    )
    );

  //密码登录
  Future<LoginModel> login(
      {required String mobile, required String memberPassword}) async {
    String md5Pass = EncryptionUtils.generateMd5(memberPassword)!;
    md5Pass = EncryptionUtils.generateMd5('${md5Pass}rl')!;

    var response = await _dio.post(
      baseUrl + loginApi,
      data: {"memberMobile": mobile, "memberPassword": md5Pass},
    );
    Loading.getIns().hide();
    if (response.statusCode == okCode) {
      LogUtils.log('登录请求成功 $response');
      if (response.data["code"] != okCodeStr) {
        ToastUtils.showToast(msg: response.data["msg"]);
      } else {
        ToastUtils.showToast(msg: loginSuccess, len: Toast.LENGTH_SHORT);
      }
      LoginModel entity = LoginModel.fromJson(response.data);
      return entity;
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return LoginModel();
    }
  }
  //验证码登录
  Future<LoginModel> smsLogin(
      {required String mobile, required String code}) async {
    var response = await _dio.post(
      baseUrl + smsLoginApi,
      data: {"memberMobile": mobile, "verifyCode": code},
    );
    Loading.getIns().hide();
    if (response.statusCode == okCode) {
      LogUtils.log('登录请求成功 $response');
      if (response.data["code"] != okCodeStr) {
        ToastUtils.showToast(msg: response.data["msg"]);
      } else {
        ToastUtils.showToast(msg: loginSuccess, len: Toast.LENGTH_SHORT);
      }
      LoginModel entity = LoginModel.fromJson(response.data);
      return entity;
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return LoginModel();
    }
  }
  //重置密码
  Future<bool> setPass(
      {required String memberMobile,
        required String verifyCode,
        required String memberPassword}) async {

    LogUtils.log('$baseUrl$resetPassApi');
    var response = await _dio.post(
      baseUrl + resetPassApi,
      data: {
        "memberMobile": memberMobile,
        "verifyCode": verifyCode,
        'memberPassword': memberPassword
      },
    );
    if (response.statusCode == okCode) {
      LogUtils.log('response=$response');
      Map<dynamic, dynamic> map = response.data;
      if (map['code'] == okCodeStr) {
        return true;
      } else {
        ToastUtils.showToast(msg: map['msg']);
        return false;
      }
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return false;
    }
  }
  //获取个人资料
  Future<DcotorModelData> doctorInfo([String id = '']) async {
    var response;
    // if (id.isEmpty) {
      response = await _dio.post(
        baseUrl + doctorInfoApi,
      );
    // } else {
    //   response = await _dio.get(
    //     baseUrl + doctorInfoApi + id,
    //   );
    // }
    if (response.statusCode == okCode) {
      LogUtils.log('获取当前医生信息$response');
      if (response.data["code"] == okCodeStr) {
        DcotorModel entity = DcotorModel.fromJson(response.data);
        return entity.data!;
      }
      return DcotorModelData();
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return DcotorModelData();
    }
  }
  //选择医院
  Future<bool> chooseHospital(String hospitalId) async {
    var response = await _dio.post(
      '$baseUrl$hospitalApi$hospitalId',
    );
    if (response.statusCode == okCode) {
      LogUtils.log('选择医院$response');
      if (response.data['code'] == okCodeStr) {
        return true;
      } else {
        return false;
      }
      // DcotorModel entity = DcotorModel.fromJson(response.data);
      // return entity;
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return false;
    }
  }
  //获取医院列表
  Future<HospitalModel> hospitalList() async {
    var response = await _dio.get(
      '$baseUrl$hospitalListApi',
    );
    LogUtils.log('response=$baseUrl$hospitalListApi');
    if (response.statusCode == okCode) {
      LogUtils.log('获取医院列表$response');
      if (response.data["code"] == okCodeStr) {
        HospitalModel entity = HospitalModel.fromJson(response.data);
        return entity;
      }
      return HospitalModel();
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return HospitalModel();
    }
  }
  //发送验证码
  Future<bool> sendCode(
      {required String codeType, required String mobile}) async {
    var response = await _dio.post(
        '$baseUrl$sendCodeApi', data: {'codeType': codeType, 'areaCode': '86', 'mobile': mobile}
    );
    if (response.statusCode == okCode) {
      Map<dynamic, dynamic> map = response.data;
      if (map['code'] == okCodeStr) {
        return true;
      } else {
        ToastUtils.showToast(msg: map['msg']);
        return false;
      }
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return false;
    }
  }
  //患者模板列表
  Future<PatientTemplateModel> patientTemplateList() async {
    var response = await _dio.post(
      '$baseUrl$patientTemplateListApi/1/1000',
      data: {'page': 1, 'size': 1000}
    );
    if (response.statusCode == okCode) {
      LogUtils.log('获取患者模板列表$response');
      if (response.data["code"] == okCodeStr) {
        PatientTemplateModel entity = PatientTemplateModel.fromJson(response.data);
        return entity;
      }
      return PatientTemplateModel();
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return PatientTemplateModel();
    }
  }
  //患者模板列表
  Future<PatientDetailEntity> patientTemplateDetail(String id) async {
    var response = await _dio.get(
      '$baseUrl$patientTemplateDetailApi$id',
      data: {'id': id}
    );
    if (response.statusCode == okCode) {
      LogUtils.log('获取患者模板详情$response');
      if (response.data["code"] == okCodeStr) {
        PatientDetailEntity entity = PatientDetailEntity.fromJson(response.data['data']);
        return entity;
      }
      return PatientDetailEntity();
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return PatientDetailEntity();
    }
  }
  //患者列表
  Future<PatientListModel> patientList(int page, String? text, [int size = 10]) async {

    Map data = {'page':page, 'size':size, 'text':text};
    var response = await _dio.post(
      '$baseUrl$patientListApi$page/$size',
      data: data
    );
    LogUtils.log('request:$baseUrl$patientListApi$page/$size');
    LogUtils.log('body=$data');
    if (response.statusCode == okCode) {
      LogUtils.log('患者列表$response');
      if (response.data["code"] == okCodeStr) {
        PatientListModel entity = PatientListModel.fromJson(response.data);
        return entity;
      }
      return PatientListModel();
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return PatientListModel();
    }
  }
  //添加患者
  Future<bool> addPatient(String templateId, List<Map<String, dynamic>> list) async {
    Map map = {'templateId':templateId, 'list':list};
    LogUtils.log('request=$baseUrl$addPatientApi');
    LogUtils.log('body=${map.toString()}');
    var response = await _dio.post(
      '$baseUrl$addPatientApi',
      data: {'templateId':templateId, 'list':list}
    );
    if (response.statusCode == okCode) {
      LogUtils.log('添加患者$response');
      if (response.data["code"] == okCodeStr) {
        return true;
      }
      return false;
      // PatientDetailEntity entity = PatientDetailEntity.fromJson(response.data['data']);
      // return entity;
    } else {
      // LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      // return PatientDetailEntity();
      return false;
    }
  }
  //患者全部标签
  Future<PatientLabelModel> patientAllLabel([int type = 1]) async {
    var response = await _dio.post(
        '$baseUrl$allPatientLabelApi',
      data: {'type': type}
    );
    LogUtils.log('request:$baseUrl$allPatientLabelApi');
    if (response.statusCode == okCode) {
      LogUtils.log('患者全部标签$response');
      if (response.data["code"] == okCodeStr) {
        PatientLabelModel entity = PatientLabelModel.fromJson(response.data);
        return entity;
      }

      return PatientLabelModel();
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return PatientLabelModel();
    }
  }
  //添加患者标签
  Future<bool> patientAddLabel(String id, List<Map<String, String>> list) async {
    var response = await _dio.post(
        '$baseUrl$addPatientLabelApi',
      data: {'id': id, 'shopLabelList': list});
    LogUtils.log('request:$baseUrl$allPatientLabelApi');
    if (response.statusCode == okCode) {
      LogUtils.log('添加患者标签$response');
      if (response.data["code"] == okCodeStr) {
        return true;
      }
      return false;
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return false;
    }
  }
  //添加患者采集标签
  Future<bool> patientAcquisitionAddLabel(String id, List<Map<String, dynamic>> list) async {
    LogUtils.log('${{'id': id, 'shopLabelList': list}}');
    var response = await _dio.post(
        '$baseUrl$addAcquisitionPatientLabelApi',
      data: {'id': id, 'shopLabelList': list});
    LogUtils.log('request:$baseUrl$addAcquisitionPatientLabelApi');
    if (response.statusCode == okCode) {
      LogUtils.log('添加患者采集标签$response');
      if (response.data["code"] == okCodeStr) {
        return true;
      }
      return false;
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return false;
    }
  }
  //添加报告采集标签
  Future<bool> reportAddLabel(String id, List<String> list) async {
    var response = await _dio.post(
        '$baseUrl$addReportLabelApi',
      data: {'id': id, 'labelIdList': list});
    LogUtils.log('request:$baseUrl$addReportLabelApi');
    LogUtils.log('body:${{'id': id, 'labelIdList': list}}');
    if (response.statusCode == okCode) {
      LogUtils.log('添加报告采集标签$response');
      if (response.data["code"] == okCodeStr) {
        return true;
      }
      return false;
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return false;
    }
  }
  //删除患者
  Future<bool> delPatient(List<int> ids) async {
    var response = await _dio.post(
        '$baseUrl$delPatientApi',
      data: ids);
    LogUtils.log('request:$baseUrl$delPatientApi');
    if (response.statusCode == okCode) {
      LogUtils.log('删除患者$response');
      if (response.data["code"] == okCodeStr) {
        return true;
      }
      return false;
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return false;
    }
  }
  //患者详情
  Future<PatientEditModel> patientDetail(String id) async {
    LogUtils.log('request:$baseUrl$patientDetailApi$id');
    var response = await _dio.get(
        '$baseUrl$patientDetailApi$id',
        data: {'id': id});
    if (response.statusCode == okCode) {
      LogUtils.log('患者详情$response');
      if (response.data["code"] == okCodeStr) {
        PatientEditModel entity = PatientEditModel.fromJson(response.data['data']);
        return entity;
      }
      return PatientEditModel();
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return PatientEditModel();
    }
  }
  //修改患者
  Future<bool> editPatient(String id, String templateId, List<Map<String, String>> list) async {
    LogUtils.log('request:$baseUrl$editPatientApi');
    var response = await _dio.post(
        '$baseUrl$editPatientApi',
        data: {'id': id, 'templateId': templateId, 'list': list});
    if (response.statusCode == okCode) {
      LogUtils.log('修改患者$response');
      if (response.data["code"] == okCodeStr) {
        return true;
      }
      return false;
    } else {
      return false;
    }
  }
  //报告列表
  Future<ReportListEntity> reportList(int page, String? text, int? sickPersonId, [int size = 10]) async {
    Map<String, dynamic> data = {'page': page, 'size': size, 'sickPersonId': sickPersonId};
    if (text != null) {
      data['text'] = text;
    }
    LogUtils.log('data=$data');

    var response = await _dio.post(
        '$baseUrl$reportListApi$page/$size',
        data: data);
    if (response.statusCode == okCode) {
      LogUtils.log('报告列表$response');
      if (response.data["code"] == okCodeStr) {
        ReportListEntity entity = ReportListEntity.fromJson(response.data);
        return entity;
      }
      return ReportListEntity();
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return ReportListEntity();
    }
  }
  //报告详情
  Future<ReportDetailEntity> reportDetail(String reportId) async {
    LogUtils.log('request:$baseUrl$reportDetailApi$reportId');
    var response = await _dio.get(
        '$baseUrl$reportDetailApi$reportId');
    if (response.statusCode == okCode) {
      LogUtils.log('报告详情$response');
      if (response.data["code"] == okCodeStr) {
        ReportDetailEntity entity = ReportDetailEntity.fromJson(response.data);
        return entity;
      }
      return ReportDetailEntity();
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return ReportDetailEntity();
    }
  }
  //报告详情
  Future<Map<String, dynamic>> reportDetailStr(String reportId) async {
    LogUtils.log('request:$baseUrl$reportDetailApi$reportId');
    var response = await _dio.get(
        '$baseUrl$reportDetailApi$reportId');
    if (response.statusCode == okCode) {
      LogUtils.log('报告详情$response');
      if (response.data["code"] == okCodeStr) {
        // ReportDetailEntity entity = ReportDetailEntity.fromJson(response.data);
        // return entity;
        return response.data['data'];
      }
      return <String, dynamic>{};
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return <String, dynamic>{};
    }
  }
  //设备列表
  Future<DeviceListEntity> deviceList() async {
    LogUtils.log('request:$baseUrl$deviceListApi');
    var response = await _dio.post(
        '$baseUrl$deviceListApi',
        data: {});
    if (response.statusCode == okCode) {
      LogUtils.log('设备列表$response');
      if (response.data["code"] == okCodeStr) {
        DeviceListEntity entity = DeviceListEntity.fromJson(response.data);
        return entity;
      }
      return DeviceListEntity();
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return DeviceListEntity();
    }
  }
  //分配设备
  Future<bool> deliveryDevice(String? id, String sickPersonId, String? deviceBluetoothNumber) async {
    var response = await _dio.post(
        '$baseUrl$deliveryDeviceApi',
        data: {'id': id, 'sickPersonId': sickPersonId, 'deviceBluetoothNumber':deviceBluetoothNumber});
    LogUtils.log('data=${{'id': id, 'sickPersonId': sickPersonId, 'deviceBluetoothNumber': deviceBluetoothNumber}}');
    LogUtils.log('url=$baseUrl$deliveryDeviceApi');

    if (response.statusCode == okCode) {
      LogUtils.log('分配设备$response');
      if (response.data["code"] == okCodeStr) {
        return true;
      }
      return false;
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return false;
    }
  }
  //解绑设备
  Future<bool> unbindDevice(String id, String recycleTime, String? recycleRemark) async {
    //1795664719974363137
    //FLEX_AIO_DA0000
    // id = '1796430974049239041';
    var response = await _dio.post(
        '$baseUrl$unbindDeviceApi',
        data: {'id': id, 'recycleTime': recycleTime, 'recycleRemark': recycleRemark});
    if (response.statusCode == okCode) {
      LogUtils.log('解绑设备成功$response');
      if (response.data["code"] == okCodeStr) {
        return true;
      }
      return false;
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return false;
    }
  }
  //设备详情
  Future<bool> deviceDetail(String id) async {
    // var id = '1795385268177911809';
    var response = await _dio.get(
        '$baseUrl$deviceDetailApi$id');
    if (response.statusCode == okCode) {
      LogUtils.log('设备详情$response');
      if (response.data["code"] == okCodeStr) {
        return true;
      }
      return false;
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return false;
    }
  }
  //患者设备列表
  Future<PatientDeviceListEntity> patientDeviceList(String sickPersonId) async {
    LogUtils.log('request:$baseUrl$patientDeviceListApi');
    LogUtils.log('sickPersonId=$sickPersonId');
    var response = await _dio.post(
        '$baseUrl$patientDeviceListApi/1/100',
        data: {"sickPersonId": sickPersonId});
    if (response.statusCode == okCode) {
      LogUtils.log('患者设备列表$response');
      if (response.data["code"] == okCodeStr) {
        PatientDeviceListEntity entity = PatientDeviceListEntity.fromJson(response.data);
        return entity;
      }
      return PatientDeviceListEntity();
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return PatientDeviceListEntity();
    }
  }
  //固件版本检测
  Future<DeviceVersionEntity> deviceVersion(String deviceType, String versionType) async {
    LogUtils.log('request:$deviceVersionApi$deviceType');
    var response = await _dio.get(
        '$deviceVersionApi$deviceType', data: {'versionType':versionType});
    if (response.statusCode == okCode) {
      LogUtils.log('固件版本检测$response');
      if (response.data["code"] == okCodeStr) {
        DeviceVersionEntity entity = DeviceVersionEntity.fromJson(response.data);
        return entity;
      }
      return DeviceVersionEntity();
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return DeviceVersionEntity();
    }
  }
  //完成人工分期
  Future<bool> resetStage(String id, List<int> stageList, List<Map<String, dynamic>> eventList) async {
    LogUtils.log('request:$deviceVersionApi$resetStageApi');
    var response = await _dio.post(
        '$baseUrl$resetStageApi', data: {'id':id, 'stageList': stageList, 'eventList': eventList});
    if (response.statusCode == okCode) {
      LogUtils.log('完成人工分期$response');
      if (response.data["code"] == okCodeStr) {
        return true;
      }
      return false;
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return false;
    }
  }

  ///文件保存在缓存目录下
  /// - `NSCachesDirectory` on iOS and macOS.
  /// - `Context.getCacheDir` on Android.
  Future<bool> downloadingFile({required String url, required String saveFileNamed}) async {
    // Directory directory = await getTemporaryDirectory();
    // String path = '${directory.path}/$saveFileNamed';
    LogUtils.log('url=$url');
    var response = await _downloadDio.download(
      url,
      saveFileNamed,
      // onReceiveProgress: (rcv, total) {
      //   if (total != -1) {
      //     print(
      //         'received: ${rcv.toStringAsFixed(0)} out of total: ${total.toStringAsFixed(0)}');
      //   }
      // },
    );
    LogUtils.log('下载任务：${response.statusCode}');
    return true;
  }
  //获取医院配置信息
  Future<HospitalCongigEntity> hospitalConfig() async {
    LogUtils.log('request:$baseUrl$hospitalConfigApi');
    var response = await _dio.get(
        '$baseUrl$hospitalConfigApi');
    if (response.statusCode == okCode) {
      LogUtils.log('获取医院配置信息$response');
      if (response.data["code"] == okCodeStr) {
        HospitalCongigEntity entity = HospitalCongigEntity.fromJson(response.data);
        return entity;
      }
      return HospitalCongigEntity();
    } else {
      LogUtils.log('发生错误, ${response.statusCode}---${response.statusMessage}');
      return HospitalCongigEntity();
    }
  }
}